//
//  HomePageViewController.m
//  GolfFriend
//
//  Created by vescky on 13-11-24.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "HomePageViewController.h"
#import "LoginPageViewController.h"
//#import "SimpleScheduleViewController.h"
#import "GolfFriendViewController.h"
//#import "OfficalViewController.h"
#import "NewsViewController.h"

#import "MJRefresh.h"
#import "DXAlertView.h"
#import "UserSession.h"
#import "UserPrivateInfoVO.h"
#import "WetherInfoVO.h"

#import "CommonUtility.h"
#import "DateUtility.h"

#import "AppsEngine.h"

#import <CoreLocation/CoreLocation.h>
#import "AppsLocationManager.h"
#import "SVProgressHUD.h"

#import "ChatListViewController.h"
#import "PublishAirticleViewController.h"
#import "NearbyFriendsViewController.h"

#import "CircleDetailViewController.h"
#import "PersonalInfoViewController.h"
//#import "CircleCommentViewController.h"
#import "MoreViewController.h"

#import "UIImageView+MJWebCache.h"

#import "ChatDAO.h"
#import "AppDelegate.h"

#import "MyCommentsViewController.h"

@interface HomePageViewController ()<GolfFriendViewDelegate,MJRefreshBaseViewDelegate,MWPickerDelegate,
UITextFieldDelegate,UIScrollViewDelegate,ToolbarViewControllerDelegate> {

//    OfficalViewController *newsView;
    NewsViewController *newsView;
    
    GolfFriendViewController *gfCircle;
    UIView *maskView;
    MWDatePicker *datePicker;
    UIToolbar *doneEdittingView;//隐藏键盘功能板
    UIButton *doneEdittingButton;
    
    //下拉刷新，上拉加载更多
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    
    float hpScrollViewLastOffset;
    bool isBackToThisView;
    
}

@end

@implementation HomePageViewController

//#pragma mark - lifeCycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
    
    if (ShowToolbarInWindow) {
        [toolBarView.view removeFromSuperview];
    }
    else {
        if (!toolBarView) {
            toolBarView = [[ToolbarViewController alloc] init];
            CGRect gfToolbarFrame = toolBarView.view.frame;
            gfToolbarFrame.origin.y = self.view.frame.size.height - gfToolbarFrame.size.height;
            toolBarView.view.frame = gfToolbarFrame;
            toolBarView.delegate = self;
            [self.view addSubview:toolBarView.view];
        }
    }
    
    [self initData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private
- (void)initData {
    labelUserName.text = [[UserSession shareUserSession] getUserName];
    labelEnName.text = [[[UserSession shareUserSession] getUserPublicInfo] objectForKey:@"enName"];
    labelTeamName.text = [[[UserSession shareUserSession] getUserPublicInfo] objectForKey:@"teamName"];
    labelMotto.text = [[[UserSession shareUserSession] getUserPublicInfo] objectForKey:@"motto"];
    if (!labelTeamName.text || labelTeamName.text.length < 1) {
        imgTeamLogo.hidden = YES;
    }
    [imgTeamLogo setImageURLStr:[[[UserSession shareUserSession] getUserPublicInfo] objectForKey:@"teamLogo"] placeholder:[UIImage imageNamed:@"default_team_logo.png"]];
    
    imgAvatar.layer.cornerRadius = imgAvatar.frame.size.width / 2.0;
    NSString *avatarLink = [[[UserSession shareUserSession] getUserPublicInfo] objectForKey:@"avatar"];
    if ([avatarLink stringByMatching:Qiniu_Domain]) {
        avatarLink = GetQiniuResizeImageLink(avatarLink, 160);
    }
    [imgAvatar setImageURLStr:avatarLink placeholder:Default_Avatar];
    
//    [self refreshMessages];
}

- (void)initView {
    //初始化刷新view
    _header = [MJRefreshHeaderView header];
    _header.scrollView = hpScrollView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.scrollView = hpScrollView;
    _footer.delegate = self;
    
    //初始化完成按键
    doneEdittingView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 35)];
    [doneEdittingView setBarStyle:UIBarStyleBlack];
    UIBarButtonItem *btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                              target:self  action:nil];
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                                target:self  action:@selector(hideKeyBoard)];
    NSArray *buttonsArry = [NSArray arrayWithObjects:btnSpace, doneButton, nil];
    [doneEdittingView setItems:buttonsArry];
    
    hpScrollView.delegate = self;
    
    if (!newsView) {
//        newsView = [[OfficalViewController alloc] init];
        newsView = [[NewsViewController alloc] init];
    }
    [newsView.view setClipsToBounds:YES];
    [hpScrollView addSubview:newsView.view];

    if (!gfCircle) {
        gfCircle = [[GolfFriendViewController alloc] init];
        gfCircle.delegate = self;
    }
    
    
    [hpScrollView addSubview:gfCircle.view];
    
    [self oganizeSubviews];
    
    [self weatherDidRefreshed];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weatherDidRefreshed) name: @"WeatherForcast" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMessages) name:Notification_Chat_Recieved object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scrollToTop) name:Notification_homepage_clicked object:nil];
}

- (void)scrollToTop {
    [hpScrollView scrollRectToVisible:CGRectMake(0, 0, hpScrollView.frame.size.width, hpScrollView.frame.size.height) animated:YES];
}

- (void)weatherDidRefreshed {
    //refresh labels
    NSUserDefaults *usd = [NSUserDefaults standardUserDefaults];
    NSDictionary *dict = [usd objectForKey:@"weatherInfo"];
    WetherInfoVO *wInfo = [[WetherInfoVO alloc] init];
    [wInfo dictionaryToWeatherInfoVO:dict];
    
    if (wInfo.cityName && wInfo.cityName.length > 0 ) {
        [labelCityName setText:wInfo.cityName];
    }
    
    if (wInfo.currentTemp && wInfo.currentTemp.length > 0) {
        [labelTemp setText:[NSString stringWithFormat:@"%@℃",wInfo.currentTemp]];//℃
    }
    
    if (wInfo.currentWeather && wInfo.currentWeather.length > 0) {
        [labelWeather setText:simplifyWeather(wInfo.currentWeather)];
    }
    
    if (wInfo.currentWeatherIcon && wInfo.currentWeatherIcon.length > 0) {
        [imgWeather0 setImage:[UIImage imageNamed:wInfo.currentWeatherIcon]];
    }
    
    if ([wInfo.sixDaysWeather count] > 1) {
        NSString *day1Weather = [wInfo.sixDaysWeather objectAtIndex:1];
        [imgWeather1 setImage:[UIImage imageNamed:getWeatherIcon(day1Weather,NO)]];
    }
    
    if ([wInfo.sixDaysWeather count] > 2) {
        NSString *day2Weather = [wInfo.sixDaysWeather objectAtIndex:2];
        [imgWeather2 setImage:[UIImage imageNamed:getWeatherIcon(day2Weather,NO)]];
    }
    
    if ([wInfo.sixDaysWeather count] > 3) {
        NSString *day3Weather = [wInfo.sixDaysWeather objectAtIndex:3];
        [imgWeather3 setImage:[UIImage imageNamed:getWeatherIcon(day3Weather,NO)]];
    }
    
    NSDate *date = [NSDate date];
    NSDate *date1 = [date dateByAddingTimeInterval:DAY_OF_SECONDS];
    NSDate *date2 = [date1 dateByAddingTimeInterval:DAY_OF_SECONDS];
    NSDate *date3 = [date2 dateByAddingTimeInterval:DAY_OF_SECONDS];
    [labelDate1 setText:getStringFromDate(@"MM月dd", date1)];
    [labelDate2 setText:getStringFromDate(@"MM月dd", date2)];
    [labelDate3 setText:getStringFromDate(@"MM月dd", date3)];
}


- (void)oganizeSubviews {
    CGRect newsViewRect = newsView.view.frame;
    newsViewRect.origin.y = personalView.frame.origin.y + personalView.frame.size.height;
    [newsView.view setFrame:newsViewRect];
    
    float gfCircleHeight = [gfCircle getTableViewHeightWithDataArray:nil];
    
    CGRect circleRect = gfCircle.view.frame;
    circleRect.origin.y = newsViewRect.origin.y + newsViewRect.size.height;
    circleRect.size.height = gfCircleHeight;
    [gfCircle.view setFrame:circleRect];
    
    [hpScrollView setContentSize:CGSizeMake(self.view.frame.size.width, circleRect.origin.y + circleRect.size.height + 50)];

}

- (void)hideKeyBoard {
    [tfAddSchedule resignFirstResponder];
}

#pragma mark - GolfFriendViewDelegate
- (void)refreshContentDidFinish {
    [_header endRefreshing];
    [self oganizeSubviews];
    NSLog(@">>>>>>>>>>>  Refresh end <<<<<<<<<<<<<<");
}
- (void)loadMoreContentDidFinish {
    [_footer endRefreshing];
    [self oganizeSubviews];
    NSLog(@">>>>>>>>>>>  Load More end <<<<<<<<<<<<<<");
}

- (void)didReachTheEndingPage {
    [SVProgressHUD showSuccessWithStatus:@"已到达最后一页"];
}

- (void)addButtonPressed {
    
}

- (void)circleCellButtonPressed:(id)sender withObject:(id)ccVo {
    UIButton *btn = (UIButton*)sender;
    if (btn.tag == 201) {
        //201 赞
    }
    else if (btn.tag == 202) {
        //202 评论
        CircleDetailViewController *vc = [[CircleDetailViewController alloc] init];
        [vc setContentVO:ccVo];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (btn.tag == 210) {
        //210 个人资料
        PersonalInfoViewController *vc = [[PersonalInfoViewController alloc] init];
        vc.userInfo = [[NSMutableDictionary alloc] initWithDictionary:[ccVo toDictionary]];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (btn.tag == 220) {
        //220 正文详情
        CircleDetailViewController *vc = [[CircleDetailViewController alloc] init];
        [vc setContentVO:ccVo];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - ToolbarViewControllerDelegate
- (void)btnClicked:(id)sender {
    UIButton *btn = (UIButton*)sender;
    
    if (btn.tag == 101) {
        [self scrollToTop];
    }
    else if (btn.tag == 102) {
        ChatListViewController *cVc = [[ChatListViewController alloc] init];
        [self.navigationController pushViewController:cVc animated:YES];
    }
    else if (btn.tag == 103) {
        PublishAirticleViewController *wVc = [[PublishAirticleViewController alloc] init];
        [self.navigationController pushViewController:wVc animated:YES];
    }
    else if (btn.tag == 104) {
        MyCommentsViewController *mVc = [[MyCommentsViewController alloc] init];
        [self.navigationController pushViewController:mVc animated:YES];
    }
    else if (btn.tag == 105) {
        [[APP_DELEGATE sidePannelController] showLeftPanelAnimated:YES];
    }
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (refreshView == _header) {
        // 下拉刷新
        [gfCircle refreshContent];
//        [self performSelector:@selector(refreshContentDidFinish) withObject:nil afterDelay:5.0];
    }
    else {
        //上拉加载更多
        [gfCircle loadMoreContent];
//        [self performSelector:@selector(loadMoreContentDidFinish) withObject:nil afterDelay:5.0];
    }
}


#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [textField setInputAccessoryView:doneEdittingView];
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    hpScrollViewLastOffset = scrollView.contentOffset.y;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < hpScrollViewLastOffset) {
        //向上,底部栏出现
        [toolBarView.view setHidden:NO];
//        [APP_DELEGATE setToolbarHidden:NO];
    }
    else if (scrollView.contentOffset.y > hpScrollViewLastOffset){
        //向下,底部栏消失
        [toolBarView.view setHidden:YES];
//        [APP_DELEGATE setToolbarHidden:YES];
    }
    
//    if (hpScrollView.contentOffset.y >= hpScrollView.contentSize.height - hpScrollView.frame.size.height - toolBarView.frame.size.height) {
//        [toolBarView setHidden:NO];
//    }
}

- (IBAction)goToPersonalView:(id)sender {
    PersonalInfoViewController *pVc = [[PersonalInfoViewController alloc] init];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:[[UserSession shareUserSession] getUserPublicInfo]];
    if ([dict objectForKey:@"uId"]) {
        [dict setObject:[dict objectForKey:@"uId"] forKey:@"userId"];
    }
    pVc.userInfo = dict;
    [self.navigationController pushViewController:pVc animated:YES];
}


@end
